<template>
    <el-form
        :model="ruleForm"
        ref="ruleFormRef"
        :rules="rules"
        label-width="70px"
        class="demo-ruleForm"
        status-icon
    >
        <!-- 标题 -->
        <el-form-item label="标题：" prop="title">
            <el-input
                type="text"
                placeholder="请输入标题"
                style="width: 300px"
                v-model="ruleForm.title"
            />
        </el-form-item>
        <!-- 文章大类 -->
        <el-form-item label="分类：" prop="articleType">
            <el-input
                type="text"
                placeholder="请输入文章分类"
                style="width: 300px"
                v-model="ruleForm.articleType"
            />
        </el-form-item>
        <!-- 文章状态 -->
        <el-form-item label="状态：" prop="status">
            <el-select
                placeholder="请选择一级类别"
                id="child"
                class="select"
                v-model="ruleForm.status"
                @change="selectChange"
            >
                <el-option
                    v-for="item in status_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </el-form-item>
        <!-- 富文本框 -->
        <el-form-item label="内容" prop="content">
            <textarea id="mytextarea" v-model="ruleForm.content"></textarea>
        </el-form-item>
        <el-form-item>
            <template #default="item">
                <el-button
                    type="primary"
                    @click="bindConfirm(ruleForm, ruleFormRef)"
                    class="sureBtn"
                    >确定</el-button
                >
                <el-button type="danger" @click="$emit('close', false)" class="cancleBtn"
                    >取消</el-button
                >
            </template>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, nextTick, reactive } from 'vue'
import { ElInput } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { RequestArticleUpload, RequestAllTypes } from '@/api/path/index.js'
const emit = defineEmits(['close'])
const ruleFormRef = ref<FormInstance>()
const childOptions = ref<any>([]) //
const file = ref('')
const userid = ref('')
userid.value = localStorage.getItem('userId')!
const type_options = ref<any>([])

// 挂载
onMounted(() => {
     // 先移除以前的
    tinymce.remove('#mytextarea');

    // tinymce.init({
    //   selector: "#mytextarea",
    //   language: "zh_CN",
    //   branding: false,
    //   height: 520,//富文本高度
    // });
    tinymce.init({
        selector: '#mytextarea',
        branding: false,
        width: 1400,
        height: 400,
        paste_data_images: true,
        // 图片上传
        images_upload_handler: function (blobInfo, success, failure) {
            file.value = blobInfo.blob()
            console.log('123', file.value)
            new Promise((resolve, reject) => {
                RequestArticleUpload({ img: file.value })
                    .then((res: any) => {
                        resolve(res)
                        success(res.resultObj)
                    })
                    .catch((err: any) => {
                        reject(err)
                        failure('请求失败')
                    })
            })
        },
        autosave_interval: '5s', //自动保存
        // selector: 'textarea',
        plugins: [
            'advlist lists link image charmap print preview anchor directionality textcolor',
            'searchreplace visualblocks code fullscreen',
            'insertdatetime media table paste help wordcount',
        ],
        fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
        font_formats:
            "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
        menubar: 'file edit view insert format tools table help ',
        toolbar:
            'undo redo | formatselect | alignleft aligncenter alignright alignjustify | indent outdent | styleselect | forecolor backcolor bold italic | fontsizeselect | fontselect | image media table | removeformat code link insertdatetime charmap print searchreplace visualblocks fullscreen wordcount paste',
        media_live_embeds: true,
        media_dimensions: false,
        style_formats: [
            { title: '首行缩进', block: 'p', styles: { 'text-indent': '2em' } },
            { title: '1.5倍行间距', selector: 'p', styles: { 'line-height': '1.5' } },
            { title: '2倍行间距', selector: 'p', styles: { 'line-height': '2' } },
            { title: '2.5倍行间距', selector: 'p', styles: { 'line-height': '2.5' } },
            { title: '字体加粗', selector: 'span,strong', styles: { 'font-weight': '600' } },
        ],
        forced_root_block: false, // 禁用默认的换行标签
        force_br_newlines: true, // 强制将换行符转换为 <br> 标签
        force_p_newlines: false, // 禁止将连续换行符转换为 <p> 标签
    })
    optionsList()
    console.log('挂载11111111111111', ruleForm.value)
})
/**
 * 获取子标题列表
 */
const optionsList = async () => {
    const a = await RequestAllTypes()
    console.log('获取子标题成功', a)
    for (let i = 0; i < a.resultObj.length; i++) {
        type_options.value.push({ value: '', lable: '' })
        ;(type_options.value[i].value = a.resultObj[i]),
            (type_options.value[i].lable = a.resultObj[i])
    }
    console.log('分类', type_options.value)
    // article_options.value = a.rows
}

// 状态大类
const status_options = [
    {
        value: 0,
        label: '已删除',
    },
    {
        value: 1,
        label: '已发布',
    },
    {
        value: 2,
        label: '已禁止',
    },
    {
        value: 3,
        label: '未发布',
    },
]
const rules = reactive({
    title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
    articleType: [{ required: true, message: '请选择文章的分类', trigger: 'change' }],
    status: [{ required: true, message: '请选择文章的分类', trigger: 'change' }],
    content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
})

// 表单回显值
const ruleForm = ref({
    title: '',
    content: '',
    articleType: '',
    ruleForm: '',
    author_id: userid.value,
    status: '',
})
// 随机切换富文本框id
const tinymceId = computed(() => {
    return `tiny-${Date.now()}`
})
const show = defineProps({
    show: {
        type: Boolean,
    },
    formdate: {
        type: Object,
    },
    type: {
        type: String,
    },
})
ruleForm.value = show.formdate //赋值

/**
 * 父标题select改变时,
 */
const selectChange = async () => {
    console.log(123)
}
/***
 * 富文本框确定事件
 */
const bindConfirm = (item, formEl: any) => {
    // 判断是否输入值
    if (!formEl) return
    const editor = tinymce.get(tinymceId.value)
    if (editor) {
        // 获取富文本框当中的值
        const content = editor.getContent()
        const plainText = content.replace(/<p>/gi, '').replace(/<\/p>/gi, '')
        console.log('富文本框值', plainText)
        ruleForm.value.content = plainText
        console.log('测试', ruleForm.value.content)
    }
    formEl.validate((valid: any, fields: any) => {
        if (valid) {
            console.log(show.type)
            if (show.type === 'Add') {
                console.log(ruleForm.value)
                new Promise((resolve, reject) => {
                    RequestArticleUpload(ruleForm.value)
                        .then((res: any) => {
                            console.log('请求成功')
                            resolve(res.data)
                            emit('close', false)
                        })
                        .catch((err: any) => {
                            console.log('请求失败')
                            reject(err.data)
                        })
                })
            } else {
                new Promise((resolve, reject) => {
                    RequestArticleUpload(ruleForm.value)
                        .then((res: any) => {
                            console.log('请求成功')
                            resolve(res.data)
                            emit('close', false)
                        })
                        .catch((err: any) => {
                            console.log('请求失败')
                            reject(err.data)
                        })
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>

<style scoped>
.el-form {
    width: 70%;
    height: 90%;
    overflow: scroll;
    position: absolute;
    top: 5%;
    left: 50%;
    margin-left: -38%;
    border: 1px solid #b9b9b9;
    padding: 30px;
    z-index: 99;
    background: #fff;
    border-radius: 10px;
}
.sureBtn {
    width: 200px;
    height: 40px;
    border-radius: 5px;
    display: block;
    margin: 10px 0px;
    margin-right: 10px;
}
.cancleBtn {
    width: 200px;
    height: 40px;
    border-radius: 5px;
    display: block;
    margin: 10px 0px;
}
.p {
    text-indent: 2em;
}
</style>
